<template>
  <x-page class="flex-row">
    <div class="left-panel">
      <div class="top">
        <el-dropdown style="margin-right: 15px" @command="handleCommand" v-hasPermi="['config:supplierType:add']">
          <el-button type="primary" plain>
            {{ $t('config.supplierType.add') }}<em class="el-icon-arrow-down el-icon--right"></em
          ></el-button>
          <el-dropdown-menu>
            <el-dropdown-item command="a">{{ $t('config.supplierType.addTop') }}</el-dropdown-item>
            <el-dropdown-item command="b">{{ $t('config.supplierType.addSon') }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <div class="tree-container">
        <div class="search-input-container">
          <el-input
            prefix-icon="el-icon-search"
            :placeholder="$t('config.supplierType.filterTxt')"
            v-model="filterText"
            style="margin-bottom: 20px"
            maxlength="100"
            clearable
          >
          </el-input>
        </div>
        <el-scrollbar style="height: calc(100% - 60px)">
          <el-tree
            :props="treeProps"
            node-key="id"
            ref="tree"
            :key="treeKey"
            default-expand-all
            :highlight-current="true"
            :filter-node-method="filterNode"
            :data="treeData"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
            :render-content="renderContent"
          ></el-tree>
        </el-scrollbar>
      </div>
    </div>
    <div class="right-panel">
      <div class="info-hearder flex-column">
        <div class="h3" v-if="currentNode?.supplierTypeName">
          <span>{{ currentNode?.supplierTypeName ?? '' }}</span>
          <el-button
            round
            size="small"
            @click="handleAdd(currentNode)"
            style="margin-left: 8px"
            v-hasPermi="['config:supplierType:add']"
          >
            {{ $t('common.edit') }}
          </el-button>
          <el-button
            round
            size="small"
            @click="handleDelete([currentNode.id])"
            style="margin-left: 8px"
            v-hasPermi="['config:supplierType:delete']"
          >
            {{ $t('common.delete') }}
          </el-button>
        </div>
        <!-- <el-breadcrumb separator-class="el-icon-arrow-right" v-if="currentNode?.path" class="sub-title">
          <el-breadcrumb-item v-for="(ele, eleIndex) in currentNode.path" :key="eleIndex">{{ ele }}</el-breadcrumb-item>
        </el-breadcrumb> -->
      </div>
      <div class="info-area">
        <span class="info">{{ $t('config.supplierType.code') }}: {{ currentNode.supplierTypeCode }}</span>
        <span class="info"
          >{{ $t('config.supplierType.siteReview') }}:
          {{ selectDictLabel(dictOptions['system.preset'], currentNode.siteReview) }}</span
        >
        <span class="info"
          >{{ $t('config.supplierType.detectMaterial') }}:
          {{ selectDictLabel(dictOptions['system.preset'], currentNode.detectMaterial) }}</span
        >
        <span class="info"
          >{{ $t('config.supplierType.isOpen') }}:
          {{ selectDictLabel(dictOptions['system.preset'], currentNode.state) }}</span
        >
      </div>
      <h4 class="sub_title">
        <em class="iconfont icon-a-Property1zuzhipeizhi"></em>
        {{ $t('config.supplierType.sub') }}
      </h4>
      <!--数据面板-->
      <x-data>
        <!--数据面板按钮插糟-->
        <template #tool>
          <el-row type="flex" class="tools" justify="space-between">
            <el-col :span="18">
              <el-button
                v-hasPermi="['config:supplierType:add']"
                v-if="currentNode?.supplierTypeName"
                round
                size="small"
                @click="handleAdd({ parentId: currentNode.id })"
              >
                {{ $t('config.supplierType.addSon') }}
              </el-button>
              <el-button
                v-hasPermi="['config:supplierType:delete']"
                round
                size="small"
                @click="handleBatchOperation('delete')"
              >
                {{ $t('common.delete') }}
              </el-button>
              <el-button
                v-hasPermi="['config:supplierType:enable']"
                round
                size="small"
                @click="handleBatchOperation('enable')"
              >
                {{ $t('config.supplierType.bantchEnable') }}
              </el-button>
              <el-button
                v-hasPermi="['config:supplierType:disable']"
                round
                size="small"
                @click="handleBatchOperation('disable')"
              >
                {{ $t('config.supplierType.bantchDisable') }}
              </el-button>
            </el-col>
            <el-col :span="6" class="tools-config">
              <x-column-config :columns="columns" @updateColumns="updateColumns" @on-refresh="loadData" />
            </el-col>
          </el-row>
        </template>
        <x-table
          ref="tableCom"
          :pagination="pagination"
          :data-source="tableData"
          :loading="loading"
          :row-key="'id'"
          @on-change="handleTableChange"
          @on-selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            v-for="(item, index) in tableColumns"
            :key="index"
            :prop="item.prop"
            :fixed="item.fixed"
            :show-overflow-tooltip="true"
            :width="item.width || 100"
            :label="item.label"
            :sortable="'custom'"
          >
            <template #default="scope">
              <el-switch
                v-if="item.prop === 'state'"
                :value="scope.row[item.prop]"
                active-color="#4474F6"
                inactive-color="#c0c4cc"
                @change="handleChangeState(scope.row[item.prop], [scope.row.id])"
                :disabled="
                  !checkBntPermi('config:supplierType:enable') && !checkBntPermi('config:supplierType:disable')
                "
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
              <x-state-cell
                v-else-if="item.prop === 'siteReview' || item.prop === 'detectMaterial'"
                :stateClass="scope.row[item.prop] === 0 ? 'danger' : scope.row[item.prop] ? 'success' : ''"
                :text="selectDictLabel(dictOptions['system.preset'], scope.row[item.prop])"
              />
              <span v-else>{{ scope.row[item.prop] | emptyVal }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" :label="$t('common.opeartion')" :align="'center'" width="160">
            <template #default="scope">
              <more-table-actions
                :action-list="actions"
                :permis-list="permissionsActions"
                :row="scope.row"
                @onActionClick="handleActions"
              />
            </template>
          </el-table-column>
        </x-table>
      </x-data>
    </div>
    <supplier-type-add
      ref="supplierTypeAddComponent"
      :dict-options="dictOptions"
      :treeData="treeData"
      :treeProps="treeProps"
      @handleSuccess="loadTreeData"
    />
  </x-page>
</template>
<script lang="jsx">
  import { selectDictLabel, TableListMixin, QueryDictMixin, PermissionsMixin } from '@package/utils'
  import { mapState } from 'pinia'
  import { pinias } from '@/common/pinia'
  import SupplierTypeAdd from '../components/supplierTypeAdd.vue'
  import { columns, actions } from '../config/supplierType'

  import {
    apiSupplierTypeTree,
    apiDeleteSupplierType,
    supplierTypePageListUrl,
    apiPutEnable,
    apiPutDisable,
    supplierTypeExportUrl
  } from '../api/supplierType'
  import { EnumApiCode } from '../../../../../../globalEnum.js'

  const { cachedView } = pinias
  export default {
    name: 'SupplierType',
    components: {
      SupplierTypeAdd
    },
    mixins: [TableListMixin, QueryDictMixin, PermissionsMixin],
    data() {
      return {
        supplierTypePageListUrl,
        supplierTypeExportUrl,
        columns,
        actions,
        filterText: '',
        isExpanded: false,
        currentNode: {},
        treeData: [],
        treeProps: {
          label: 'supplierTypeName',
          children: 'children'
        },
        treeKey: '1',
        tableData: [],
        disableMixinCreated: true,
        creatFlag: false,
        dictKeys: ['system.state', 'system.preset'],
        selectionData: []
      }
    },
    computed: {
      ...mapState(cachedView, ['visitedViews']),
      listUrl() {
        return this.supplierTypePageListUrl
      },
      otherParam() {
        return { parentId: this.currentNode?.id ?? '' }
      }
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val)
      }
    },
    mounted() {
      this.creatFlage = true
      this.loadTreeData()
      this.initDictConfig()
    },
    activated() {
      const temp = this.visitedViews.filter((v) => v.path === this.$route.path)
      if (this.disableMixinCreated && this.creatFlag && !temp) {
        this.loadTreeData()
      }
    },
    methods: {
      selectDictLabel,
      async loadTreeData() {
        const { data, code, msg } = await apiSupplierTypeTree()
        if (code === EnumApiCode.Success) {
          this.treeData = data || []
          if (!this.currentNode && this.treeData?.length) {
            this.currentNode = this.treeData[0] || {}
          }
          this.treeKey = Math.random()
          this.$nextTick(() => {
            this.currentNode && this.refrenTreeCurrent(this.currentNode.id)
          })
        } else {
          this.$message.error(msg)
        }
      },
      refrenTreeCurrent(key) {
        this.$nextTick(() => {
          // 双重判定，历史选中节点是否存在于树节点上
          const isCheck = this.$refs.tree.getNode(key)
          if (!isCheck) {
            this.currentNode = this.treeData[0] || {}
          }
          this.$refs.tree.setCurrentKey(this.currentNode.id)
          const data = this.$refs.tree.getCurrentNode()
          const node = this.$refs.tree.getNode(this.currentNode.id)
          node && this.handleNodeClick(data, node)
        })
      },
      getDictLabel(list, value) {
        return selectDictLabel(list, value)
      },
      renderContent(h, { node, data, store }) {
        let nodeClass = ''
        if (data.state === 0) {
          nodeClass = 'gray'
        }
        return (
          <div className="custom-tree-node">
            <span className={nodeClass} title={node.label}>
              {node.label}
            </span>
          </div>
        )
      },
      filterNode(value, data) {
        if (!value) return true
        return data[this.treeProps.label].indexOf(value) !== -1
      },
      async handleChangeState(state, ids) {
        const { code, msg } = state === 1 ? await apiPutDisable(ids) : await apiPutEnable(ids)
        if (code === EnumApiCode.Success) {
          this.$message.success(this.$t('system.user.successTips'))
          this.handleSearch()
        } else {
          this.$message.error(msg)
        }
      },
      handleNodeClick(data, node) {
        this.currentNode.path = []
        this.currentNode = JSON.parse(JSON.stringify(data))
        if (node.parent.data.id) {
          this.currentNode.path = [node.parent.data.supplierTypeName, this.currentNode.supplierTypeName]
        }
        this.handleSearch()
      },
      handleCommand(command) {
        if (command === 'a') {
          this.$refs.supplierTypeAddComponent.handleOpen({ parentId: 0 }, false)
        } else if (command === 'b') {
          this.$refs.supplierTypeAddComponent.handleOpen({ parentId: this.currentNode.id })
        }
      },
      handleAdd(info) {
        this.$refs.supplierTypeAddComponent.handleOpen(info)
      },
      handleExport() {
        this.handleExport(this.supplierTypeExportUrl)
      },
      handleActions({ key, data }) {
        switch (key) {
          case 'edit': // 修改供应商类型基本信息
            this.$refs.supplierTypeAddComponent.handleOpen(data)
            break
          case 'delete':
            this.$confirm(this.$t('system.user.deleteSure'), this.$t('system.user.deletePrompt'), {
              confirmButtonText: this.$t('common.confirm'),
              cancelButtonText: this.$t('common.cancel'),
              type: 'warning'
            })
              .then((confirm) => {
                this.handleDelete([data.id])
              })
              .catch((cancel) => {})
            break
          default:
            break
        }
      },
      /**
       * 列表选中数据
       *
       */
      handleSelectionChange(data) {
        this.selectionData = data
      },
      // 批量操作
      handleBatchOperation(flag) {
        if (this.selectionData.length == 0) {
          this.$message.error('请选择至少一条数据进行操作')
        } else {
          const ids = this.selectionData.map((item) => {
            return item.id
          })
          const tip = flag === 'delete' ? '删除' : flag === 'enable' ? '启用' : '停用'
          this.$confirm(`确认批量${tip}吗?`, '提示', {
            confirmButtonText: this.$t('common.sure'),
            cancelButtonText: this.$t('common.cancel')
          })
            .then(() => {
              flag === 'delete' && this.handleDelete(ids)
              flag !== 'delete' && this.handleChangeState(flag === 'enable' ? 0 : 1, ids)
            })
            .catch(() => {})
        }
      },
      /**
       * 删除
       * @param deptId 供应商类型ID string
       */
      handleDelete(ids) {
        apiDeleteSupplierType(ids).then((res) => {
          if (res.code === EnumApiCode.Success) {
            this.$message.success(this.$t('common.deleteSuccess'))
          } else {
            this.$message.error(res.msg)
          }
          this.loadTreeData()
          this.loadData()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import '../../../common/assets/style/variables';

  .flex-row {
    display: flex;
    flex-direction: row;

    .left-panel {
      flex: 1;
      min-width: 300px;
      border-radius: 3px;
      background-color: $x-default-bg-color;

      .top {
        margin-bottom: 16px;
        padding: 12px 15px;
        border-bottom: 1px solid #e0e0e0;
      }

      .tree-container {
        height: calc(100% - 100px);
        .search-input-container {
          padding: 0 15px;
        }
      }

      ::v-deep .custom-tree-node {
        color: #333;

        .gray {
          color: #c0c4cc;
        }
      }
    }

    .right-panel {
      display: flex;
      flex: 5;
      flex-direction: column;
      max-width: calc(100% - 300px);
      margin-left: 10px;
      color: #424242;
      border-radius: 3px;
      background-color: $x-default-bg-color;
      .info-area {
        font-size: 16px;
        padding-left: 20px;
        margin-bottom: 16px;
        span {
          padding-right: 16px;
        }
      }
      h4,
      .h3 {
        font-size: 20px;
        font-weight: 500;
        margin: 0;
        // padding: 0 20px;

        span {
          line-height: 30px;
        }
      }

      h4 {
        margin-bottom: 19px;
        padding: 0 20px;

        .iconfont {
          font-size: 20px;
        }
      }

      h3 {
        padding-top: 20px;
      }

      .el-breadcrumb.sub-title {
        font-size: 14px;
        line-height: 36px;
        padding-left: 7px;
      }

      .x-data-view {
        margin-top: 0;
        padding-top: 0;
        border-width: 0;
      }

      .tools {
        line-height: 42px;
        padding: 0 15px;
        border-radius: 3px;
        background-color: #eceff4;
      }

      .info-container {
        padding: 0 15px;
      }

      .info-hearder {
        font-size: 16px;
        padding: 15px;
        // padding-left: 15px;
        color: $x-item-text-color;
        // border-bottom: 1px solid #e0e0e0;

        .el-icon-edit-outline {
          font-size: 18px;
          vertical-align: middle;
        }
      }
    }
  }
</style>

<style lang="scss">
  /* element滚动条组件 隐藏水平滚动条 */
  .tree-container .el-scrollbar__view {
    padding: 0 15px;
  }
  .tree-container .el-scrollbar__wrap {
    overflow-x: hidden;
  }

  .is-horizontal {
    display: none;
  }
</style>
